
<template>
  <div class="content">
    <!-- 表格 -->
    <a-table
        :columns="interfaceColumns"
        :data-source="interfaceData"
        :pagination="{ pageSize: 10, current: currentPage, total: totalInterfaces }"
        @change="handleTableChange"
        bordered
    >
      <template #headerCell="{ column }">
        <template v-if="column.key === 'name' || column.key === 'description' || column.key === 'url'">
          <div class="table-header">
            <span>{{ column.title }}</span>
            <a-dropdown :trigger="['click']" v-if="!searchState[column.key + 'Visible']">
              <a class="ant-dropdown-link" @click.prevent="toggleSearch(column.key)">
                <search-outlined />
              </a>
            </a-dropdown>
            <a-input
                v-if="searchState[column.key + 'Visible']"
                v-model:value="searchForm[column.key]"
                :placeholder="'搜索' + column.title"
                style="width: 120px; margin-left: 8px"
                @change="debouncedSearch"
                @blur="searchState[column.key + 'Visible'] = false"
                allowClear
            />
          </div>
        </template>
        <template v-else>
          {{ column.title }}
        </template>
      </template>
      
      <template #bodyCell="{ column, record }">
        <template v-if="column.editable">
          <div v-if="editingKey === record.id">
            <a-input
                v-if="column.dataIndex === 'name'"
                v-model:value="editForm.name"
                style="margin: -5px 0"
            />
            <a-input
                v-else-if="column.dataIndex === 'description'"
                v-model:value="editForm.description"
                style="margin: -5px 0"
            />
            <a-input
                v-else-if="column.dataIndex === 'url'"
                v-model:value="editForm.url"
                style="margin: -5px 0"
            />
            <a-select
                v-else-if="column.dataIndex === 'method'"
                v-model:value="editForm.method"
                style="width: 100%"
            >
              <a-select-option value="GET">GET</a-select-option>
              <a-select-option value="POST">POST</a-select-option>
              <a-select-option value="PUT">PUT</a-select-option>
              <a-select-option value="DELETE">DELETE</a-select-option>
            </a-select>
          </div>
          <div v-else>
            {{ record[column.dataIndex] }}
          </div>
        </template>
        <template v-else-if="column.key === 'action'">
          <div v-if="editingKey === record.id">
            <a-button type="link" @click="saveEdit(record.id)">保存</a-button>
            <a-button type="link" @click="cancelEdit">取消</a-button>
          </div>
          <div v-else>
            <a-button type="link" @click="edit(record)">编辑</a-button>
          </div>
        </template>
      </template>
    </a-table>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { InterfaceInfoControllerService } from '../openapi/api';
import { SearchOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { useUserStore } from '../stores/userStore';

// 添加防抖函数
const debounce = (fn, delay = 500) => {
  let timer = null;
  return function(...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};


const userStore = useUserStore();
const editVisible = ref(false);
const searchForm = ref({
  id: null,
  name: '',
  description: '',
  url: '',
  status: null,
  method: '',
  createUserId: null,
  createTime: null
});

// 添加搜索状态
const searchState = ref({
  nameVisible: false,
  descriptionVisible: false,
  urlVisible: false
});

const editForm = ref({});
const editingKey = ref('');
const interfaceData = ref([]);
const currentPage = ref(1);
const totalInterfaces = ref(0);

const interfaceColumns = [
  { 
    title: 'ID', 
    dataIndex: 'id',
    key: 'id',
    width: 80
  },
  { 
    title: '接口名称', 
    dataIndex: 'name',
    key: 'name',
    editable: true
  },
  { 
    title: '接口描述', 
    dataIndex: 'description',
    key: 'description',
    editable: true
  },
  { 
    title: '接口地址', 
    dataIndex: 'url',
    key: 'url',
    editable: true
  },
  { 
    title: '状态', 
    dataIndex: 'status',
    key: 'status',
    editable: true
  },
  { 
    title: '请求类型', 
    dataIndex: 'method',
    key: 'method',
    editable: true
  },
  { 
    title: '创建人', 
    dataIndex: 'createUserId',
    key: 'createUserId'
  },
  { 
    title: '创建时间', 
    dataIndex: 'createTime',
    key: 'createTime'
  },
  { 
    title: '操作', 
    key: 'action',
    width: 120
  }
];



const toggleSearch = (key) => {
  searchState.value[key + 'Visible'] = true;
};

const edit = (record) => {
  if (!userStore.isLoggedIn) {
    userStore.showLoginModal();
    return message.warning('请登录后操作！');
  }
  editingKey.value = record.id;
  editForm.value = { ...record };
};

const saveEdit = async (id) => {
  try {
    await InterfaceInfoControllerService.updateUsingPost({
      updateRequest: {
        id: id,
        ...editForm.value,  // 展开 editForm 中的值到 updateRequest 对象
      }
    });
    editingKey.value = '';
    message.success('修改成功');
    handleSearch();
  } catch (error) {
    console.error('更新接口错误:', error);
    message.error(`修改失败: ${error.message || '未知错误'}`);
  }
};

const cancelEdit = () => {
  editingKey.value = '';
};


const handleSearch = async () => {
  try {
    // 新增登录检查
    if (!userStore.isLoggedIn) {
      userStore.showLoginModal();
      return message.warning('请先登录！');
    }
    console.log('搜索参数:', searchForm.value);
    const params = {
      ...searchForm.value,
      current: currentPage.value,
      pageSize: 10
    };
    const response = await InterfaceInfoControllerService.pageQueryUsingPost({ queryRequest: params });
    interfaceData.value = response.data.records;
    totalInterfaces.value = response.data.total;
  } catch (error) {
    // 新增401状态处理
    if (error.response?.status === 401) {
      userStore.showLoginModal();
      return message.warning('登录已过期，请重新登录！');
    }
    console.error('搜索接口失败:', error);
  }
};

// 创建带防抖的搜索函数
const debouncedSearch = debounce(handleSearch);

const handleTableChange = (pagination) => {
  currentPage.value = pagination.current;
  handleSearch();
};

onMounted(() => {
  handleSearch();
});
</script>

<style scoped>
.table-header {
  display: flex;
  align-items: center;
}

.ant-dropdown-link {
  margin-left: 8px;
  color: rgba(0, 0, 0, 0.45);
  cursor: pointer;
}

.ant-dropdown-link:hover {
  color: #1890ff;
}
</style>